#!/bin/bash
# description:
#	set wsl proxy,using clash, port 7890
# install:
# 	add source wsl-proxy.sh to alias
# usage:
#	1. echo proxy information
#	wsl-proxy.sh test	
#	2. set proxy
#	wsl-proxy.sh set
#	3. unset proxy
#	wsl-proxy.sh unset
# Author: Zinglix
#	Modified from page: https://zinglix.xyz/2020/04/18/wsl2-proxy/
# Date: 2022/2/21
# Log:
#	2022/2/21	ver1.0	create

######## Custom function define ########
check_alias () {
	# check whether set alias or not
	# if not, export will not work
	Result=$(alias |grep -c 'source proxy.sh')
 	case $Result in
		0 )
			echo "add following line to .bashrc"
			echo "alias proxy='source proxy.sh'"
			exit 1
			;;
	esac
}
# 3 mod, set / unset /test
set_proxy () {
	export http_proxy="$PROXY_HTTP"
	export https_proxy="$PROXY_HTTP"
	git config --global http.proxy "$PROXY_HTTP"
	git config --global https.proxy "$PROXY_HTTP"
}

unset_proxy () {
	unset http_proxy
	unset https_proxy
	git config --global --unset http.proxy
	git config --global --unset https.proxy
}

test_setting () {
	echo "Host ip:${HOST_IP}"
	echo "Current proxy:${https_proxy}"
	echo "git proxy:"
	echo "$(git config --global -l |grep proxy)"
}

get_host_ip () {
	echo 127.0.0.1
}

check_alias
######## Get IP ########
HOST_IP=$(get_host_ip)
PORT=7890

PROXY_HTTP="http://${HOST_IP}:${PORT}"


case "$1" in
	set ) set_proxy;;
	unset ) unset_proxy;;
	test ) test_setting;;
esac
